package com.example.zhinongbao.adapter;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.zhinongbao.R;
import com.example.zhinongbao.bean.Article;
import com.example.zhinongbao.utils.Constant;
import com.example.zhinongbao.utils.FragmentUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章适配器
 */
public class SchoolContentAdapter extends RecyclerView.Adapter<SchoolContentAdapter.ViewHolder> {
    private List<Article> mDataList = new ArrayList<>();

    public SchoolContentAdapter(List<Article> dataList) {
        this.mDataList = dataList;
    }

    @NonNull
    @Override
    public SchoolContentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_school_content, parent, false);
        SchoolContentAdapter.ViewHolder holder = new SchoolContentAdapter.ViewHolder(view);
        return holder;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Article article = mDataList.get(position);
        holder.item_school_content_title.setText(article.getTitle());
        holder.item_school_content_time.setText(article.getTime());
        holder.item_school_content_views.setText(article.getViews() + "");
        holder.item_school_content_image.setImageURI(Uri.parse(article.getImageUri()));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 保存当前点击的文章到全局变量中，跳转到文章页面
                Constant.currentArticle = article;
                FragmentUtils.getInstance().switchFragment(R.id.nav_article);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (mDataList != null) {
            return mDataList.size();
        }
        return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView item_school_content_title;
        TextView item_school_content_time;
        TextView item_school_content_views;
        ImageView item_school_content_image;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            item_school_content_title = itemView.findViewById(R.id.item_school_content_title);
            item_school_content_time = itemView.findViewById(R.id.item_school_content_time);
            item_school_content_views = itemView.findViewById(R.id.item_school_content_views);
            item_school_content_image = itemView.findViewById(R.id.item_school_content_image);
        }
    }
}
